import json
from openai import OpenAI
from openai import AsyncOpenAI
import json
from typing import Dict, Any
import asyncio


API_KEY = "sk-be2d84b850604504bf412db080c98d8e"

client = OpenAI(
    api_key=API_KEY,
    base_url="https://api.deepseek.com",
)


# 初始化异步客户端
aclient = AsyncOpenAI(
    api_key=API_KEY,  # 替换为你的 DeepSeek/OpenAI API 密钥
    base_url="https://api.deepseek.com/v1"  # DeepSeek API 地址
)


def get_ans_json(user_prompt):


    messages = [
        {"role": "system", "content": "return json"},
        {"role": "user", "content": user_prompt}
    ]

    response = client.chat.completions.create(
        model="deepseek-chat",
        messages=messages,
        response_format={
            'type': 'json_object'
        }
    )

    return json.loads(response.choices[0].message.content)




async def get_ans_json_async(user_prompt: str) -> Dict[str, Any]:
    """
    使用 OpenAI 官方异步接口获取 JSON 响应
    
    Args:
        user_prompt: 用户提示文本
        
    Returns:
        JSON 格式的响应字典
        
    Raises:
        openai.APIError: API 请求失败
        json.JSONDecodeError: 响应不是有效 JSON
    """
    try:
        response = await aclient.chat.completions.create(
            model="deepseek-chat",
            messages=[
                {"role": "system", "content": "return json"},
                {"role": "user", "content": user_prompt}
            ],
            response_format={"type": "json_object"},
            temperature= 0 
        )
        
        # 解析 JSON 响应
        return json.loads(response.choices[0].message.content)
        
    except json.JSONDecodeError as e:
        raise ValueError(f"Invalid JSON response: {str(e)}")

if __name__ == "__main__":

    # user_input = "世界上最长的河流是哪条？"
    # result = get_ans_json(user_input)
    # print(result)



    user_input = "世界上最长的河流是哪条？"
    
    # 方法1：使用 asyncio.run() 运行异步函数
    result = asyncio.run(get_ans_json_async(user_input))
    print(result)